package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.jsc.mapper.UniversityDigitalizationMapper;
import com.cmii.sjw.department.control.jsc.model.UniversityDigitalization;
import com.cmii.sjw.department.control.jsc.model.dto.UniversityDigitalizationDTO;
import com.cmii.sjw.department.control.jsc.service.UniversityDigitalizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;


@Slf4j
@Service("UniversityDigitalizationService")
public class UniversityDigitalizationServiceImpl extends ServiceImpl<UniversityDigitalizationMapper, UniversityDigitalization> implements UniversityDigitalizationService {


    /**
     * 高校核心业务数字化率统计表
     *
     * @return 列表
     */
    @Override
    public List<UniversityDigitalization> list() {
        LambdaQueryWrapper<UniversityDigitalization> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(UniversityDigitalization::getDigitalizationRate);
        return list(wrapper);
    }

    /**
     * 核心业务事项数字化统计
     *
     * @return 统计数据
     */

    @Override
    public UniversityDigitalizationDTO getDigitalizationStats() {
        List<UniversityDigitalization> list = this.list();

        int totalCatalog = 0;
        int totalDigitalized = 0;
        BigDecimal totalRate = BigDecimal.ZERO;

        for (UniversityDigitalization item : list) {
            totalCatalog += Optional.ofNullable(item.getCatalogCount()).orElse(0);
            totalDigitalized += Optional.ofNullable(item.getDigitalizedCount()).orElse(0);
            totalRate = totalRate.add(Optional.ofNullable(item.getDigitalizationRate()).orElse(BigDecimal.ZERO));
        }

        UniversityDigitalizationDTO stats = new UniversityDigitalizationDTO();
        stats.setTotalCatalogCount(totalCatalog);
        stats.setTotalDigitalizedCount(totalDigitalized);
        if (!list.isEmpty()) {
            BigDecimal avgRate = totalRate.divide(BigDecimal.valueOf(list.size()), 2, RoundingMode.HALF_UP);
            stats.setAverageDigitalizationRate(avgRate);
        } else {
            stats.setAverageDigitalizationRate(BigDecimal.ZERO);
        }

        return stats;
    }
}
